//index.js
//获取应用实例
const app = getApp();
let videoAd = null;
let timer = null;
Page({
    data: {
        isLogin: false,
        is_advert: 0,
        b_id: '',
        navIndex: 2,
        taskData: [],
        limit: wx.getStorageSync('daliyTaskLimit').limit,
        limitSecond: wx.getStorageSync('daliyTaskLimit').limitSecond,
        videoCompleteNum: 0,
    },
    onLoad: function() {
        var that = this, limitSecond = 15, r = Math.floor(Math.random()*3);
        that.setData({
            is_advert: app.globalData.is_advert,
            b_id: app.globalData.b_id,
            limit: wx.getStorageSync('daliyTaskLimit').limit,
            limitSecond: wx.getStorageSync('daliyTaskLimit').limitSecond,
        });

        // 在页面onLoad回调事件中创建激励视频广告实例
        if (wx.createRewardedVideoAd) {
            videoAd = wx.createRewardedVideoAd({
                adUnitId: app.globalData.v_id
            })
            videoAd.onLoad(() => {console.log('视频加载成功！')})
            videoAd.onError((err) => {
                app.showError(err.errCode + ' ' +  err.errMsg);
            })
            videoAd.onClose((res) => {
                //console.log(res);
                if(res.isEnded){ 
                    if(that.data.videoCompleteNum > 5) limitSecond = 30;
                    if(that.data.videoCompleteNum > 8) limitSecond = 60;

                    wx.setStorageSync('daliyTaskLimit', { limit: true, limitSecond: limitSecond });
                    that.setData({ limit: true });
                    that.countDown();  

                    var data = {
                        openid: app.globalData.openid || wx.getStorageSync('openid'),
                        id: '5',
                        task_id: app.globalData.b_id,
                        tsp: Math.floor(new Date().getTime() / 1000),
                    };

                    data.sign = app.getSign(data);

                    wx.request({
                        url: app.globalData.Baseurl + 'DailyTask/completeNewTask',
                        method: 'GET',
                        data: data,
                        success: function(res) {
                            that.getTaskList();
        
                        }
                    });
                }
            });
        }
    },
    onShow: function() {
        this.setData({ isLogin: app.globalData.isLogin });
        this.getTaskList();

        clearTimeout(wx.getStorageSync('daliyTaskLimitTime'));
        this.countDown();
    },
    Login: function(){
        wx.navigateTo({
            url: '/pages/Authorized/Authorized',
        });
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        var that = this;
        app.onLaunch(function() {
            that.onShow();
        });
    },
    /**
     * 广告间隔倒计时
     */
    countDown: function() {
        var t = this, s = wx.getStorageSync('daliyTaskLimit').limitSecond;
        console.log('countDown' + "--" + s);

        if(s > 0){
            t.setData({ limitSecond: s - 1 });
            wx.setStorageSync('daliyTaskLimit', { limit: true, limitSecond: s - 1 });
        }else{
            t.setData({ limit: false });
            wx.setStorageSync('daliyTaskLimit', { limit: false, limitSecond: 0 });
            return false;
        }

        timer = setTimeout(t.countDown, 1000);
        wx.setStorageSync('daliyTaskLimitTime', timer);
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        
    },

    getPhoneNumber:   function(e)  {  
        let that = this;
        
        if(e.detail.errMsg == 'getPhoneNumber:ok'){ 
            wx.showModal({          
                title:   '提示',
                showCancel:  false,
                content:   '同意授权',
                success:   function (res)  {
                    // console.log(res)
                    wx.request({
                        url: app.globalData.Baseurl + 'Login/gettell',
                        data: {
                            encryptedData: e.detail.encryptedData,
                            code: app.globalData.code,
                            iv: e.detail.iv,
                            openid: app.globalData.openid || wx.getStorageSync('openid'),
                            sessionKey: app.globalData.session_key
                        },
                        success: function(res) {
                            // console.log(res)
                            that.completeTask(e.currentTarget.dataset.id);
                        }
                    });
                }      
            });   
        }else { 
            wx.showModal({          
                title:   '提示',
                showCancel:  false,
                content:   '未授权',
                success:   function (res)  { }      
            });    
        }
    },

    /**
     * 导航切换
     */

    navSwitch: function(e){
        var id = e.currentTarget.dataset.id;

        this.setData({ navIndex: id });

        this.getTaskList();
    },
    // 
    getTaskList: function() {
        var that = this;
        var data = {
            openid: app.globalData.openid || wx.getStorageSync('openid'),
            type: that.data.navIndex,
            tsp: Math.floor(new Date().getTime() / 1000),
        };

        data.sign = app.getSign(data);

        wx.request({
            url: app.globalData.Baseurl + 'DailyTask/taskCenterList',
            method: 'GET',
            data: data,
            success: function(res) {
                if(res.data.status == 1){
                    for(var i in res.data.data){
                        res.data.data[i].s_num = res.data.data[i].num - res.data.data[i].complete_num;
                        if(res.data.data[i].s_num > 0) res.data.data[i].is_complete = 0;
                        if(res.data.data[i].s_num == 0) res.data.data[i].is_complete = 1;
                    }

                    if(res.data.data.video) that.setData({ videoCompleteNum: res.data.data.video.complete_num });

                    that.setData({ taskData: res.data.data });
                }
            }
        })
    },
    toTask: function(e){
        var id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index;

        if(index == 'sign') this.toSign();
        if(index == 'niu' || index == 'share') this.toNdj();
        if(index == 'dian') this.toXd();
        if(index == 'egg') this.toSelectXd();
        if(index == 'zan') this.toIndex();
        if(index == 'video') this.toVideo(id);
        if(index == 'guang') this.toMiniProgram(id);
        if(index == 'investigation') this.toTaskOut(id);
        if(index == 'shua') this.shuashua(id);
        if(index == 'vip') this.toVip(id);
    },
    //每日签到
    toSign: function(){
        wx.navigateTo({
            url: '../Sign/sign',
        })
    },
    //开心扭蛋
    toNdj: function() {
        wx.navigateTo({
            url: '../ndj/list',
        });
    },
    //闲蛋
    toXd: function() {
        wx.navigateTo({
            url: '../xd/xd?isAss=0',
        });
    },
    //领养闲蛋
    toSelectXd: function() {
        wx.navigateTo({
            url: '../xd/list',
        });
    },
    //开通会员
    toVip: function(){
        wx.navigateTo({
            url: '../person/member',
        });
    },
    //赞一赞
    toIndex: function() {
        wx.navigateTo({
            url: '../index/index',
        });
    },
    //看一看
    toVideo: function(id) {

        // 用户触发广告后，显示激励视频广告
        if (videoAd) {
            videoAd.show().catch(() => {
                // 失败重试
                videoAd.load().then(() => videoAd.show()).catch(err => {
                    console.log("视屏show的log：" + err.errCode + ' ' +  err.errMsg);
                    // app.showError('激励视频 广告显示失败,请刷新页面重试');
                })
            })
        }
        // wx.navigateTo({
        //     url: '../taskVideo/index?id=' + id,
        // });
    },
    //问卷调查
    toTaskOut: function(id) {
        var that = this;
        var data = {
            openid: app.globalData.openid || wx.getStorageSync('openid'),
            id: id,
            tsp: Math.floor(new Date().getTime() / 1000),
        };

        data.sign = app.getSign(data);

        wx.request({
            url: app.globalData.Baseurl + 'DailyTask/specificTaskList',
            method: 'GET',
            data: data,
            success: function(res) {
                if(res.data.status == 1){
                   //存入本地存储
                     // wx.setStorage({ key: 'outUrl', data: res.url });
                    // wx.navigateTo({
                    //     url: '../out/out?',
                    // }); 
                }
            }
        });
    },
    //逛一逛
    toMiniProgram: function(id){
        var that = this;
        var data = {
            openid: app.globalData.openid || wx.getStorageSync('openid'),
            id: id,
            tsp: Math.floor(new Date().getTime() / 1000),
        };

        data.sign = app.getSign(data);

        wx.request({
            url: app.globalData.Baseurl + 'DailyTask/specificTaskList',
            method: 'GET',
            data: data,
            success: function(res) {
                if(res.data.status == 1){
                   wx.navigateToMiniProgram({
                        appId: res.data.data.appid, // 要跳转的小程序的appid
                        path: res.data.data.url, // 跳转的目标页面
                        extarData: {
                            open: 'auth'
                        },
                        success(r) {
                            // 打开成功 
                            that.completeTask(id, res.data.data.task_id);
                        }
                    });  
                }
            }
        })
            
    },
    //刷一刷
    shuashua: function(id) {
        var that = this;
        wx.navigateToMiniProgram({
            appId: 'wxfc10495d086cdfdf', // 要跳转的小程序的appid
            path: 'zh_tcwq/pages/index/index', // 跳转的目标页面
            extarData: {
                open: 'auth'
            },
            success(res) {
                // 打开成功 
                that.completeTask(id);
            }
        });
    },

    /**
     * 完成任务
     */
    completeTask: function(id, task_id){
        var that = this;
        var data = {
            openid: app.globalData.openid || wx.getStorageSync('openid'),
            id: id,
            tsp: Math.floor(new Date().getTime() / 1000),
        };

        if(task_id) data.task_id = task_id;

        data.sign = app.getSign(data);

        wx.request({
            url: app.globalData.Baseurl + 'DailyTask/completeNewTask',
            method: 'GET',
            data: data,
            success: function(res) {
                that.onShow();
            }
        });
    },
    

     
     /**
      * 时间戳转换成 时间  年月日 时 分
      */
    timeFormat: function(time, type) {
        if(!time) return "---";
        var d = new Date(1000*time);
        var yy = d.getFullYear();
        var mm = d.getMonth() + 1;
        var dd = d.getDate();
        var hh = d.getHours();
        var ff = d.getMinutes();

        if(mm < 10) mm = "0" + mm;
        if(dd < 10) dd = "0" + dd;
        if(hh < 10) hh = "0" + hh;
        if(ff < 10) ff = "0" + ff;

        if(type == 1) return yy + "." + mm + "." + dd;
        if(type == 2) return yy + "-" + mm + "-" + dd;
        if(type == 3) return yy + "-" + mm + "-" + dd + " " + hh + ":" + ff;
    },

    /**
     * 页面相关事件处理函数--监听页面滚动
     */
    onPageScroll: function(e) {

    },
})